package com.demo.springmvc.controller;

import com.demo.springmvc.common.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Controller
public class ResultDemoController {
//    老掉牙的东西，原理很简单
    @RequestMapping("/rsdemo1")
    public ModelAndView testrs(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("ok");
        mv.addObject("name","ModelAndView 中的name内容！");
        return mv;
    }

//    Model , ModelMap
    @RequestMapping("/rsdemo2")
    public String testrs2(/*Model model*/ModelMap modelMap/*, HttpServletRequest request*/){
       // model.addAttribute("name","Model 中的name内容！");
        modelMap.put("name","ModelMap 中的name内容！");
       /* request.setAttribute("myname","???");*/
        return "ok";
    }

//     spring mvc 重定向到页面
    @RequestMapping("/rsdemo3")
    public String testrs3(/*Model model*/ModelMap modelMap){
        // model.addAttribute("name","Model 中的name内容！");
        modelMap.put("name","modelMap 中的name内容！");
        return "redirect:/okpage";
    }

    @RequestMapping("/okpage")
    public String testrs33(/*Model model*/ModelMap modelMap){
        return "ok";
    }

    @RequestMapping("/rsdemo4")
    @ResponseBody //把返回结果json 序列化后，输出到浏览器
    public Object testrs4(){
        Map<String,Object> map = new HashMap<>();
        map.put("name","张三");
        map.put("sex",true);
        map.put("age",21);
        return map;
    }

    //通过servlet 原生api，直接输出
    @RequestMapping("/rsdemo5")
    public Object testrs5(HttpServletResponse response){
        try {
            PrintWriter writer = response.getWriter();
            writer.println("this is  output from response！！");
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


}
